package net.xdclass.xdclassmq.jms.producer;

import net.xdclass.xdclassmq.config.JmsConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Component
public class PayProducer {

    @Autowired
    private JmsConfig jmsConfig;

    private static volatile DefaultMQProducer producer = null;

    public PayProducer() {
    }

    public DefaultMQProducer getProducer(){
        if(null == producer){
            synchronized (PayProducer.class){
                if(null == producer){
                    producer = new DefaultMQProducer(jmsConfig.getPayProducerGroup());

                    //指定NameServer地址，多个地址以 ; 隔开
                    //producer.setNamesrvAddr("192.168.40.134:9876,192.168.40.135:9876");
                    producer.setNamesrvAddr(jmsConfig.getNameServerAddr());
                    start();
                }
            }
        }
        return producer;
    }

    /*public DefaultMQProducer getProducer() {
        return this.producer;
    }*/

    /**
     * 对象在使用之前必须要调用一次，只能初始化一次
     */
    public void start(){
        try {
            this.producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 一般在应用上下文，使用上下文监听器，进行关闭
     */
    public @PreDestroy void shutdown(){
        System.out.println("关闭连接");
        this.producer.shutdown();
    }
}
